package manager

import (
	"errors"
	"fmt"
	"os"

	"gitee.com/ideadawn/dbvm/util"
)

// Deploy 部署到指定版本
func (m *Manager) Deploy(to string, forces []string) error {
	logs, err := m.engine.ListLogs()
	if err != nil {
		return err
	}

	lastPos := len(m.plans) - 1
	if to == `latest` {
		if lastPos >= 0 {
			to = m.plans[lastPos].Name
		}
	}
	for i := range forces {
		if forces[i] == `latest` && lastPos >= 0 {
			forces[i] = m.plans[lastPos].Name
		}
	}

	notFound := true
	for _, plan := range m.plans {
		for _, log := range logs {
			if log.Name == plan.Name {
				plan.deployed = true
				m.deployed[log.Name] = true
				break
			}
		}

		if to == plan.Name {
			if plan.deployed && !util.StrInArr(plan.Name, forces) {
				fmt.Printf("Version( %s ) was deployed.\n", to)
				return nil
			}
			notFound = false
		}
	}

	if notFound {
		return errors.New(`Version not found: ` + to)
	}

	for _, plan := range m.plans {
		if plan.deployed && !util.StrInArr(plan.Name, forces) {
			continue
		}
		for _, req := range plan.Requires {
			if _, ok := m.deployed[req]; !ok {
				return fmt.Errorf("Deploy %s need %s , check your plans", plan.Name, req)
			}
		}

		info, err := os.Stat(plan.Deploy)
		if err != nil || info.IsDir() {
			return fmt.Errorf("Deploy-File ( %s ) check failed: %s", plan.Deploy, err.Error())
		}
		info, err = os.Stat(plan.Revert)
		if err != nil || info.IsDir() {
			return fmt.Errorf("Revert-File ( %s ) check failed: %s", plan.Revert, err.Error())
		}

		err = m.engine.Deploy(plan)
		if err != nil {
			return err
		}

		plan.deployed = true
		m.deployed[plan.Name] = true
		fmt.Println(plan.Name, `deployed.`)

		if to == plan.Name {
			break
		}
	}

	return nil
}
